package com.dalianpai.gulimall.product.web;

import com.dalianpai.gulimall.product.entity.CategoryEntity;
import com.dalianpai.gulimall.product.service.CategoryService;
import com.dalianpai.gulimall.product.vo.Catalog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author WGR
 * @create 2020/6/18 -- 20:05
 */
@Controller
public class IndexController {

    @Autowired
    CategoryService categoryservice;
    @Autowired
    RedissonClient redisson;

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping({"/", "index.html"})
    public String indexPage(Model model) {
        List<CategoryEntity> categoryEntities = categoryservice.getLevel1Categorys();
        model.addAttribute("categorys", categoryEntities);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        Map<String, List<Catalog2Vo>> map = categoryservice.getCatalogJson();
        return map;
    }

    /**
     * 简单请求
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        RLock rLock = redisson.getLock("my-lock");
        //1.锁的自动续期，如果业务超长，运行期间会自动给锁续上新的30s。不用担心业务时间长，锁自动被删掉
        //2.加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁默认在30s以后自动删除。
        //rLock.lock();
        rLock.lock(30, TimeUnit.SECONDS);  //10秒自动解锁，自动解锁时间一定要大于业务的执行时间
        //问题：rLock.lock(10, TimeUnit.SECONDS);  在锁时间到了以后，不会自动续期
        //1.如果我们传递了锁的超时时间，就发送给redis执行脚本，进行占锁，默认超时就是我们指定的时间。
        //2.如果我们未指定锁的超时时间，就使用30*1000的LockWatchTimeout看门狗的默认时间；
        // 只要占锁成功，就会启动一个定时任务，每隔10s都会自动续期
        //建议； rLock.lock(30, TimeUnit.SECONDS); 省掉了续期的时间
        try {
            System.out.println("加锁成功，执行业务"+Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch(Exception e){

        }finally {
            System.out.println("释放锁"+Thread.currentThread().getId());
            rLock.unlock();
        }

        return "hello";
    }

    //保证一定能读到最新数据，修改期间，写锁是一个排他锁(互斥锁)。读锁是一个共享锁
    //写锁没释放读就必须等待
    //读 + 读： 相当于无锁，并发读，只会在redis中记录好，所有当前的读锁。他们都会同时加锁成功
    //写 + 读： 等待写锁释放
    //写 + 写： 阻塞方式
    //读 + 写： 有读锁。写也需要等待
    //只要有写的存在，都必须等待。
    @GetMapping("/write")
    @ResponseBody
    public String writeValue(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.writeLock();
        try {
            rLock.lock();
            s = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set("writeValue",s);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return  s;

    }

    @GetMapping("/read")
    @ResponseBody
    public String read(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.readLock();
        try {
            rLock.lock();
            Thread.sleep(30000);
            s = redisTemplate.opsForValue().get("writeValue");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return  s;

    }


    @GetMapping("/lockDoor")
    @ResponseBody
    public  String lockDoor () throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();
        return "放假了。。。";
    }

    @GetMapping("/gogogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable("id") Long id){
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();
        return id+"班的人都走了";
    }

    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException{
        RSemaphore park = redisson.getSemaphore("park");
        park.acquire();
        return "ok";
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException{
        RSemaphore park = redisson.getSemaphore("park");
        park.release();
        return "ok";
    }


}